<template>
  <d2-container>
    <div style="margin: 20px">
      <el-card>
        <div slot="header" class="clearfix">
          <div>
            <span style="text-align: left; font-size: 28px; color: #1E90FF"><b>| </b></span>
            <span style="text-align: left; font-size: 22px"><b>模型信息</b></span>
          </div>
        </div>
        <el-form label-width="100px" label-position="left" size="large" :model="form" :rules="rules" ref="testForm">
          <el-form-item label="选择项目" prop="project">
            <el-select clearable v-model="form.project" placeholder="请选择" style="width: 40%"
                       :disabled="isDisabled" ref="projectRef" value-key="id" @change="selectProjectChange">
              <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择模型" prop="model">
            <el-select clearable v-model="form.model" placeholder="请选择" style="width: 40%"
                       :disabled="isDisabled" ref="modelRef" @change="selectModelChange">
              <!--              <el-option v-for="item in models" :key="item.id" :label="item.name.substring(0, item.name.length-36)"-->
              <!--                         :value="item.id">-->
              <!--              </el-option>-->
              <el-option v-for="item in models" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择图像源" prop="datasource">
            <el-select clearable v-model="form.datasource" placeholder="请选择" style="width: 40%"
                       @change="selectDatasourceChange">
              <el-option v-for="item in datasource" :key="item.id" :label="item.label" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择图片" prop="image" v-if="form.datasource===2" :required="true">
            <el-select clearable v-model="form.image" placeholder="请选择" style="width: 40%"
                       @change="selectImageChange">
              <el-option v-for="item in srcList" :key="item.id" :label="item.name"
                         :value="'http://127.0.0.1:9000/' + item.src + '/' +　item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :limit="fileLimit"
            :before-upload="beforeUpload"
            :on-change="submitUpload"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :auto-upload="false"
            accept=".png,.jpg,.jpeg"
            list-type="picture">

            <el-button :style="{ display: visible }" v-if="form.datasource===1" size="small" type="primary"
                       @click="addParam">点击上传测试图片
            </el-button>
            <div slot="tip" :style="{ display: visible }" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form>
        <div style="float:right; margin-top: 10px;padding-bottom: 10px">
          <el-button :disabled="disabled" type="primary" size="medium" autocomplete="off" @click="submit">开始测试
          </el-button>
        </div>
      </el-card>

      <el-card style="margin-top: 20px">
        <div slot="header" class="clearfix">
          <div>
            <span style="text-align: left; font-size: 28px; color: #1E90FF"><b>| </b></span>
            <span style="text-align: left; font-size: 22px"><b>识别效果</b></span>
          </div>
        </div>
        <div class="pro" v-if="!videoVisible">
          <div class="left">
            <div class="demo-image__error">
              <div class="block">
                <el-image :src="imgUrl">
                  <div slot="placeholder" class="image-slot">
                    加载中<span class="dot">...</span>
                  </div>
                  <div slot="error" class="image-slot" v-if="imgUrl.length===0">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
          </div>
        </div>
        <div class="pro" v-if="videoVisible">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>取图方式</span>
                </div>
                <el-table :data="CameratableData" style="width: 100%" border>
                  <el-table-column prop="name" label="名称" width="80" align="center"/>
                  <el-table-column prop="url" label="地址" width="150" align="center"/>
                  <el-table-column prop="screentype" label="取图类型" :show-overflow-tooltip="true" width="80"
                                   align="center"/>
                  <el-table-column prop="interval" label="取图间隔" :show-overflow-tooltip="true" width="80"
                                   align="center"/>
                  <el-table-column prop="total" label="取图数量" :show-overflow-tooltip="true" width="80"
                                   align="center"/>
                  <el-table-column fixed="right" label="操作" width="160" align="center">
                    <template slot-scope="scope">
                      <el-button slot="reference" size="mini" type="primary" @click="start(scope)"
                                 style="margin-right: 5px">启用
                      </el-button>
                      <el-button slot="reference" size="mini" @click="stop(scope)" style="margin-right: 5px">暂停
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="box-card" style="overflow: auto">
                <div slot="header" class="clearfix">
                  <span>画面预览</span>
                </div>
                <div>
                  <el-image style="width: 100%;height: auto" :src="picSrc"></el-image>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </d2-container>
</template>

<script>
import {GetModelList, GetModelObj, GetPredict, GetProList, Stop, Upload} from './api'
import util from '@/libs/util'
import {Loading} from 'element-ui'
import {GetList} from '@/views/datasource/camerascreentype/api'

export default {
  name: 'index',
  data() {
    return {
      // 摄像机相关参数
      videoVisible: false,
      opArr: [],
      typeParams: {},
      CameratableData: [],
      picSrc: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      form: [],
      projects: [],
      isDisabled: false,
      models: [],
      datasource: [
        {id: 1, label: '上传'},
        {id: 2, label: '图片源'},
        {id: 3, label: '视频源'}
      ],
      srcList: [],
      rules: {
        project: [
          {required: true, message: '请选择项目', trigger: 'change'}
        ],
        model: [
          {required: true, message: '请选择模型', trigger: 'change'}
        ],
        datasource: [
          {required: true, message: '请选择图像源', trigger: 'change'}
        ]
      },
      // 开始测试按钮
      disabled: true,
      // 上传按钮
      visible: 'none',
      // 允许的文件类型
      fileType: ['png', 'jpg', 'jpeg'],
      // 运行上传文件大小，单位 M
      fileSize: 10,
      // 附件数量限制
      fileLimit: 1,
      // 上传携带的参数
      uploadData: '',
      uploadUrl: util.baseURL() + 'ai/models/file/',
      uploadHeaders: {
        Authorization: 'JWT ' + util.cookies.get('token')
      },
      headers: {'Content-Type': 'multipart/form-data'},
      imgUrl: ''
    }
  },
  methods: {
    // 开启摄像机
    async start(scope) {
      this.typeParams = scope.row
      this.opArr = this.form.model
      this.picSrc = `http://127.0.0.1:8000/datasource/video/?params=${JSON.stringify(this.typeParams)}&op=${JSON.stringify(this.opArr)}`
    },
    // 暂停摄像机
    async stop(scope) {
      this.typeParams = scope.row
      this.opArr = this.form.model
      this.picSrc = 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
      Stop(JSON.stringify(this.typeParams), JSON.stringify(this.opArr))
    },
    // 获取相机列表
    async getTableData() {
      const res = await GetList()
      console.log(res)
      if (res.code === 2000) {
        this.CameratableData = res.data.data
      } else {
        this.$message.error(res.msg)
      }
    },
    // 获取所有模型
    getModels() {
      GetModelList().then(response => {
        this.models = response.data.data
      })
    },
    // 获取所有项目
    getProjects() {
      const query = {creator_id: this.$store.state.d2admin.user.info.user_id}
      GetProList(query).then(response => {
        this.projects = response.data.data
      })
    },
    // 根据项目获取对应模型
    selectProjectChange(item) {
      // 清空上次选择的模型
      this.visible = 'none'
      this.$set(this.form, 'model', '')
      const data = []
      for (let i = 0; i < item.children.length; i++) {
        if (item.children[i].status === 2) { // 模型训练完成
          data.push(item.children[i])
        }
      }
      this.models = data
    },
    // 选择模型后才可上传图片
    selectModelChange(item) {
      // 清空文件上传列表
      this.$refs.upload.clearFiles()
      this.disabled = true
      if (item === '') {
        this.visible = 'none'
      }
    },
    // 选择图像源
    selectDatasourceChange(item) {
      // 清空文件上传列表
      this.$refs.upload.clearFiles()
      this.disabled = true
      this.$set(this.form, 'image', '')
      if (item === 1) { // 上传
        this.visible = ''
        this.videoVisible = false
      } else if (item === 2) { // 图片源
        this.videoVisible = false
        this.rules.image = [
          {required: true, message: '请选择图片', trigger: 'change'}
        ]
        this.visible = 'none'
        // 请求/datasource/pic, 并将返回的数据赋值给orderFormData.params.src.options
        this.$axios({
          url: '/datasource/picture',
          method: 'get',
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'JWT ' + util.cookies.get('token')
          }
        }).then((res) => {
          this.srcList = res.data.data.data
          console.log('图片源', this.srcList)
        })
      } else if (item === 3) { // 视频源
        this.videoVisible = true
      }
    },
    // 选择图片
    selectImageChange(item) {
      this.disabled = false
      // 选中图片后将图片复制到模型测试路径
      const modelID = this.$refs.modelRef.selected.value
      if (item !== '' && item !== null) {
        Upload(item, modelID).then(response => {
        })
      }
    },
    // 启动模型测试
    submit() {
      // 启动loading服务
      const loadingInstance = Loading.service({
        target: document.getElementById('detailClass'),
        fullscreen: true,
        text: '已提交测试，请稍候...',
        background: 'rgba(225,225,225,0.8)'
      })
      this.$refs.testForm.validate(async (valid) => {
        if (valid) {
          GetPredict(this.form.model).then(response => {
            // 关闭loading
            loadingInstance.close()
            this.imgUrl = 'data:image/jpeg;base64,' + response.data
          })
        } else {
          return false
        }
      })
    },
    // 根据模型ID获取所属的项目
    getPro(modelID) {
      this.getProjects()
      GetModelObj(modelID * 1).then(response => {
        for (let i = 0; i < this.projects.length; i++) {
          if (this.projects[i].id === response.data.project) {
            this.form.project = this.projects[i]
          }
        }
      })
    },
    // 文件上传
    submitUpload() {
      this.disabled = false
      this.$refs.upload.submit()
    },
    // 文件移除
    handleRemove() {
      this.disabled = true
    },
    // 超出文件个数的回调
    handleExceed() {
      this.$message({
        type: 'warning',
        message: '超出最大上传文件数量的限制！'
      })
    },
    // 上传失败
    handleError() {
      this.$message.error('上传失败')
    },
    // 上传携带的参数(模型ID)
    addParam() {
      this.uploadData = {id: this.$refs.modelRef.selected.value}
    },
    // 上传文件之前
    beforeUpload(file) {
      if (file.type !== '' || file.type != null || file.type !== undefined) {
        // 截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, '').toLowerCase()
        // 计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 50 // 这里做文件大小限制
        // 如果大于50M
        if (!isLt5M) {
          this.$showMessage('上传文件大小不能超过 50MB!')
          return false
        }
        // 如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true
        } else {
          this.$message.error('上传文件格式不正确!')
          return false
        }
      }
    },
    async loadInitialData(modelID) {
      this.getProjects()
      this.getTableData()
      if (modelID) {
        this.getModels()
        this.form.project = 0
        this.form.model = parseInt(modelID)
        const project = await this.getProjectByModelID(modelID)
        this.form.project = project
        this.isDisabled = true
        this.visible = ''
      }
    },
    async getProjectByModelID(modelID) {
      const response = await GetModelObj(parseInt(modelID))
      const project = this.projects.find(p => p.id === response.data.project)
      return project || 0
    }
  },
  created: function () {
    const modelID = this.$route.query.id
    this.loadInitialData(modelID)
  }
}
</script>

<style scoped>

.pro {
  margin: 10px 0;
  width: 100%;
  height: 100%;
}

.left {
  width: 48%;
  height: 100%;
  float: left;
}

.right {
  width: 50%;
  height: 100%;
  float: right;
}
</style>
